<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class FavourController extends Controller
{
    public function __construct(Request $request)
    {
        if (!$request->expectsJson()) {
            $this->middleware('auth');
        }
    }


    public function make(Request $request, $model, $id)
    {
        $model = $this->model();
        if ($request->expectsJson()) {
            //@ $click 异步时按钮的状态true选中，false未选中
            return $this->asyncMake($model, $id);
        } else {
            return $this->syncMake($model, $id);
        }
    }

    protected function asyncMake($model, $id)
    {
        $click = request()->input('click');
        if (Auth::check() && $click) {
            $model->favour();
            $route = false;
        } else {
            $url = request()->input('preUrl');
            session(['preUrl' => $url]);
            $route = route('login');
        }

        return response()->json(['isFavorite' => $model->isFavour, 'favoriteCount' => $model->favour_count, 'route' => $route]);

    }

    protected function syncMake($model, $id)
    {
        $model->favour();
        return back();
    }

    public function model()
    {
        $class = 'Modules\Edu\Entities\\' . request()->model;
        return app($class)->find(request()->id);
    }

}
